<?php


namespace app\api\controller\v15;


use app\api\controller\v13\Auth2;
use app\astro\controller\Data;
use app\astro\controller\Planetpower;
use app\astro\controller\Signscore;
use app\common\cachemodel\Astro;
use app\common\cachemodel\NatalGoods;
use app\common\cachemodel\NatalReport;
use app\common\cachemodel\SystemConfig;
use app\common\lib\Natal;
use app\common\lib\Util;
use app\common\model\Recode;
use think\Env;
use think\Log;

/**
 * 星盘星座页面
 * @version 1.10.1
 * Class AstroSign
 * @package app\api\controller\v15
 */
class AstroSign extends Auth2
{
    protected $msg;
    protected $button = [
        'des' => '你的运势和机遇'
    ];

    /**
     * 获取星座信息
     * @return \think\response\Json
     * @throws \app\common\lib\exception\ApiException
     * @throws \Exception
     */
    public function signInfo()
    {
        $rid = input('param.rid/d', 0);
        $sign_id = input('param.in_sign/d', 0);
//        $sign_id = $sign_id <= 0 || $sign_id > 12 ? 8 : $sign_id;// 默认天蝎座
        $utilModel = new Util();
        //  获取系统配置
        $config = (new SystemConfig())->getSystemConfig(['title1', 'title_intro1', 'title2', 'title_intro2']);
        if ($this->user && $rid)
        {
            $recode = (new \app\common\cachemodel\Recode())->getInfoById($rid);
            if (!$recode || $recode['uid'] != $this->user['id'])
            {
                return show(config('code.error'), '当前档案不存在');
            }
            if ($recode['isself'])
            {
                $name = '自己';
            } else
            {
                $name = mb_substr($recode['name'], 0, 4);
            }
            $sun = mb_substr($utilModel->recodeAstro($recode['sun']), 0, 2);
            $moon = mb_substr($utilModel->recodeAstro($recode['moon']), 0, 2);
            $asc = mb_substr($utilModel->recodeAstro($recode['asc']), 0, 2);
            $data = [
                'button_title' => '一生报告',
                'button_des' => $this->button['des'],
                'sign_info' => [
                    'sun_in_sign' => $name . '是' . $sun . '座',
                    'birth_date_info' => '日' . $sun . '月' . $moon . '升' . $asc
                ],
            ];
            $totalScore = $this->getTotalScore($rid);
            $sign_score = $totalScore['sign_score'];
            $planet_power = $totalScore['planet_power'];
            $new_sign_score = [
                'title' => '星座成分',
                'score' => [],
            ];
            $new_planet_power = [
                'title' => '行星能量',
                'list' => $planet_power,
            ];
            foreach ($sign_score as $value)
            {
                $planet_name = [];
                foreach ($value['in_sign'] as $item)
                {
                    $planet_id = (int)$item['id'];
                    $planet_info = mb_substr($utilModel->PlanetTypeName($planet_id), 0, 1);
                    if ($planet_info === '太')
                    {
                        $planet_info = '日';
                    } elseif ($planet_info === '上')
                    {
                        $planet_info = '升';
                    }
                    $planet_name[] = $planet_info;
                }
                $new_sign_score['score'][] = [
                    'sign_id' => $value['id'],//星座id
                    'planets_name_list' => $planet_name,//行星名称列表
                    'percent' => round($value['percent'], 2),//占比
                    'tags' => $value['tags']//标签
                ];
            }
            $data['sign_score'] = $new_sign_score;
            $data['astro_explain_url'] = Env::get('host.domain') . '/web/astro_explain_new/index.html?rid=' . $rid;
            $data['planet_power'] = $new_planet_power;
            $data['natal_report']['title'] = (isset($config['title1']) && !empty($config['title1'])) ? $config['title1'] : '';
            $data['natal_report']['title_intro'] = (isset($config['title_intro1']) && !empty($config['title_intro1'])) ? $config['title_intro1'] : '';
            $data['natal_report']['info_list'] = $this->NatalInfo($rid);
        } elseif ($sign_id)
        {
            if (!in_array($sign_id, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], true))
            {
                return show(config('code.error'), '当前星座超出认知范围');
            }
            $sign_info = $utilModel->signTypeName($sign_id);
            $data = [
                'button_title' => '一生报告',//(isset($config['title1']) && !empty($config['title1'])) ? $config['title1'] : ''
                'button_des' => $this->button['des'],
                'sign_info' => [
                    'sun_in_sign' => '太阳在' . $sign_info['name'],
                    'birth_date_info' => '出生日期：' . $sign_info['date'],
                    'sign_info_text' => $sign_info['des']
                ],
            ];
        } else
        {
            Log::write('获取星座信息缺少请求参数：' . json_encode(input('param.'), true), 'error', true);
            if ($this->request->header('version') === '2.5.0' && $this->request->header('app-type') === 'android')
            {
                return show(config('code.error'), '请登录应用后重试');
            }
            return show(config('code.error'), '请退出应用后重试');
        }

        return show(config('code.success'), '获取成功', $data);
    }

    /**
     *  获取人生分数
     * @param int $rid
     * @return array
     * @throws \app\common\lib\exception\ApiException
     * @throws \Exception
     */
    protected function getTotalScore($rid)
    {
        $Data = new Data();
        $map = ['id' => $rid, 'uid' => $this->user['id']];

        $RecodeModel = new Recode();
        $AstroModel = new Astro();

        $userinfo = $RecodeModel->getRecode($map);
        $timestamp1 = $Data->deal_time($userinfo);

        $utdatenow = strftime('%d.%m.%Y', $timestamp1);
        $utnow = strftime('%H:%M:%S', $timestamp1);

        $longitude = ($userinfo['long_deg'] + $userinfo['long_min'] / 60) * $userinfo['ew'];
        $latitude = ($userinfo['lat_deg'] + $userinfo['lat_min'] / 60) * $userinfo['ns'];

        $Data->planets_display = '111111111100100001001';
        $Data->asps_display = [0, 60, 90, 120, 180];
        $Data->asp_orb_all = [0 => 8, 60 => 6, 90 => 7, 120 => 7, 180 => 7, 30 => 1, 150 => 2, 45 => 2, 135 => 2, 72 => 2, 144 => 2];
        $Data->planet_orb_all = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        $hys = 'p';

        $options = ['utdatenow' => $utdatenow, 'utnow' => $utnow, 'longitude' => $longitude, 'latitude' => $latitude, 'h_sys' => $hys];

        $out = $Data->execData($options);

        $original_data = $Data->getOriginalData($out, $hys);
        $Data->array_remove($original_data, $Data->planets_display);
        $details = $Data->getPlanetHouseDetail($original_data, $original_data['hc1'], $userinfo['year']);

        $phase = $Data->planetPkPlanet($original_data, $original_data, true);
        foreach ($phase['planets'] as $k => $d)
        {
            $details['planets'][$k]['phase'] = $d['phase'];
            if (empty($d['phase'])) $details['planets'][$k]['phase'] = null;
        }

        $details['phase'] = $phase['phase'];
        $details['characteristic'] = $Data->recept_or_mutual_recept($details['planets']);

        $details = $AstroModel->get_structure($details);

        $data = [];
        $SignscoreModel = new Signscore($details);
        $PlanetpowerModel = new Planetpower($details);
        $data['sign_score'] = $SignscoreModel->_initload($rid);
        $data['planet_power'] = $PlanetpowerModel->_initload();
        return $data;
    }

    /**
     * 获取取`本命预测信息
     * @param $rid
     * @return array
     * @throws \Exception
     */
    private function NatalInfo($rid)
    {
        $recodeModel = new Recode();
        $NatalReportModel = new NatalReport();
        if ($rid)
        {
            $recodeInfo = $recodeModel->getRecode(['uid' => $this->user['id'], 'id' => $rid]);
        } else
        {
            $recodeInfo = $recodeModel->getSelfRecode(['uid' => $this->user['id']]);
            $rid = $recodeInfo['id'];
        }
        //  获取分数及词条
        $natal = (new Natal())->getScoreAndText($recodeInfo);
        //  获取本命预测商品信息
        $goodData = (new NatalGoods())->getGoods();
        // 获取解锁订单信息状态
        $unlockReport = $NatalReportModel->getNatalReport2($recodeInfo);
        // $unlockReport = $NatalReportModel->getNatalReport($this->user['id'], $rid);

        $forecast = [];
        $oldNatalScore = ['feelings' => 'love', 'dating' => 'home', 'carrer' => 'work', 'money' => 'money', 'academic' => 'study'];
        foreach (array_values($goodData) as $key => $item)
        {
            if ($item['status'] == 2)//暂不开放状态
            {
                $status = 3;
            } else//判断商品解锁状态
            {
                if (isset($unlockReport[$item['id']]))
                {
                    $unlock_status = (int)$unlockReport[$item['id']]['status'] === 2 ? 2 : 1;
                    $status = isset($unlockReport[$item['id']]) ? ($unlock_status) : 0;
                } else
                {
                    $status = 0;
                }
            }
            $d = [
                'gid' => (int)$item['id'],
                'score' => $natal[$oldNatalScore[$item['flag']]] ?? 0,
                'text' => $natal[$oldNatalScore[$item['flag']] . '_text'] ?? '',
                'status' => $status,
                'alert_bg_img1' => $item['alert_bg_img1'] ?? '',
                'alert_bg_img2' => $item['alert_bg_img2'] ?? '',
                'gcolor' => $item['color'] ?? '',
                'gname' => $NatalReportModel->gidName[$item['flag']] ?: '',
            ];

            $forecast[] = $d;
        }

        return $forecast;
    }
}
